package cn.sfrog.system.service.impl;

import cn.sfrog.common.annotation.DataSource;
import cn.sfrog.common.constant.ConfigConstants;
import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.constant.UserConstants;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.core.text.Convert;
import cn.sfrog.common.enums.DataSourceType;
import cn.sfrog.common.exception.ServiceException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.system.domain.SysConfig;
import cn.sfrog.system.domain.vo.SysDataVO;
import cn.sfrog.system.mapper.SysConfigMapper;
import cn.sfrog.system.service.ISysConfigService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

/**
 * 参数配置 服务层实现
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService {
    @Resource
    private SysConfigMapper configMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public SysConfig selectConfigById(Long configId) {
        SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
//        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
//        if (StringUtils.isNotEmpty(configValue)) {
//            return configValue;
//        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if (StringUtils.isEmpty(captchaOnOff)) {
            return true;
        }
        return Convert.toBool(captchaOnOff);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        return configMapper.selectConfigList(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        int row = configMapper.insertConfig(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        int row = configMapper.updateConfig(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     * @return 结果
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 " , config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            redisCache.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
        for (SysConfig config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config) {
        Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());
        if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveSysConfig(SysDataVO dataVO) {
        Field[] declaredFields = dataVO.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            try {
                // 保存参数
                saveConfigData(JSON.parseObject(declaredField.get(dataVO).toString()));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return 1;
    }

    @Override
    public SysDataVO selectSysConfigInfo() {
        SysDataVO sysDataVO = new SysDataVO();
        sysDataVO.setEscortBeanExchangeScaleJson(setConfigData(ConfigConstants.ESCORT_BEAN_EXCHANGE_SCALE));
        sysDataVO.setSignInDistanceJson(setConfigData(ConfigConstants.SIGN_IN_DISTANCE));
        sysDataVO.setEscortSureMoneyJson(setConfigData(ConfigConstants.ESCORT_SURE_MONEY));
        sysDataVO.setCareWorkerSureMoneyJson(setConfigData(ConfigConstants.CAREWORKER_SURE_MONEY));
        sysDataVO.setDoctorSureMoneyJson(setConfigData(ConfigConstants.DOCTOR_SURE_MONEY));
        sysDataVO.setFirstDistributionScaleJson(setConfigData(ConfigConstants.FIRST_DISTRIBUTION_SCALE));
        sysDataVO.setSecondDistributionScaleJson(setConfigData(ConfigConstants.SECOND_DISTRIBUTION_SCALE));
        sysDataVO.setSecondDistributionScaleJson(setConfigData(ConfigConstants.SECOND_DISTRIBUTION_SCALE));
        sysDataVO.setOrderCommissionScaleJson(setConfigData(ConfigConstants.ORDER_COMMISSION_SCALE));
        sysDataVO.setDonateLimitJson(setConfigData(ConfigConstants.DONATE_LIMIT));
        return sysDataVO;
    }

    private void saveConfigData(JSONObject obj) {
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        String key = obj.getString(ConfigConstants.KEY);
        String name = obj.getString(ConfigConstants.NAME);
        String value = obj.getString(ConfigConstants.VALUE);
        // 根据key查询是否已添加该参数
        SysConfig sysConfig = configMapper.checkConfigKeyUnique(key);
        if (sysConfig != null) {
            sysConfig.setConfigValue(value);
            sysConfig.setUpdateTime(DateUtils.getNowDate());
            sysConfig.setUpdateBy(userName);
            configMapper.updateConfig(sysConfig);
        } else {
            sysConfig = new SysConfig();
            sysConfig.setConfigKey(key);
            sysConfig.setConfigName(name);
            sysConfig.setConfigValue(value);
            sysConfig.setConfigType(ConfigConstants.Y);
            sysConfig.insert();
        }
    }

    private String setConfigData(String configKey) {
        String jsonStr = "";
        JSONObject jsonObject = new JSONObject();
        SysConfig sysConfig = configMapper.checkConfigKeyUnique(configKey);
        if (sysConfig != null) {
            jsonObject.put(ConfigConstants.KEY, sysConfig.getConfigKey());
            jsonObject.put(ConfigConstants.NAME, sysConfig.getConfigName());
            jsonObject.put(ConfigConstants.VALUE, sysConfig.getConfigValue());
        } else {
            jsonObject.put(ConfigConstants.VALUE, "");
        }
        jsonStr = jsonObject.toJSONString();
        return jsonStr;
    }
}
